package hottargui.view;

import hottargui.domain.*;

import minidraw.framework.*;
import java.awt.Point;
import java.awt.event.MouseEvent;

/** MyUnitMoveTool: 
 * 
 * 
 * A wrapper for the UnitMoveTool that handels the proces of buying and placing 
 * units.
 * The class catches if a zero-buy was made. A zero-byt happends when    	
 * a unit in treassury is moved/tutch just a bit.
 * 
 */

public class MyUnitBuyTool extends UnitMoveTool {

	/** UnitMoveTool's internal state is like SelectionTool defined
      by a subtool */

	private Point _startPoint, _endPoint;
	private Game _game;
	private boolean _treasuryMove; 
	private Drawing _drawing; 

	// TODO: refactor to use an object server instead
	public MyUnitBuyTool(DrawingEditor editor, Game game) {
		super(editor, game);
		_game = game;  
		_treasuryMove = true;
		_drawing = editor.drawing();
	}  




	public void mouseDown(MouseEvent e, int x, int y) {

		//System.out.println("BuyTool: Var her ..... mouseDown");
		_startPoint = new Point(x,y);

		Position
		boardStartPosition = mouse2pos(_startPoint);



		_treasuryMove =
			boardStartPosition.getColumn() > 6;	

			if (_treasuryMove)       
				super.mouseDown(e, x, y);

	}  


	public void mouseDrag(MouseEvent e, int x, int y) {
		//System.out.println("Buy Tool: Der dragges");
		super.mouseDrag(e, x, y);
	}


	public void mouseMove(MouseEvent e, int x, int y) {
		super.mouseMove(e, x, y);
	}



	public void mouseUp(MouseEvent e, int x, int y) {

		_endPoint = new Point(x,y);  
		//System.out.println("BuyTool: Var her ..... mouseUp");


		Position 
		boardEndPosition = mouse2pos(_endPoint);	

		_treasuryMove =
			boardEndPosition.getColumn() > 6;	


			Player p = _game.getPlayerInTurn();       
			Boolean hasNoUnitsInTreasury = hasNoUnitsInTreasury(p); 

			//Zero buy ... the units are again placed on treasury signaling
			//that the player dosn't wanne buy anything
			// if no units in trasury a clik on the trasury is enough

			if ((_treasuryMove && calculateUnitsInSelection(_drawing) >0 )
					|| (_treasuryMove && hasNoUnitsInTreasury))
			{
				_game.buy(0,null);

			}	

			super.mouseUp(e, x, y);


	}





	/** convert a mouse position to board position. TODO: Refactor */
	private Position mouse2pos(Point p) {
		Position
		pos =
			TarguiViewDefinition.getTilePositionFromXY(p.x, p.y);
		return pos;
	}  



	private int calculateUnitsInSelection(Drawing d) {
		int unitsToMove = 0;
		for ( Figure f: d.selection() ) {
			UnitFigure uf = (UnitFigure) f;
			if ( uf.getType() == UnitFigure.UnitType.FIVE ) {
				unitsToMove += 5;
			} else {
				unitsToMove++;
			}
		}
		return unitsToMove;
	}







	//TODO: Refactor
	private boolean hasNoUnitsInTreasury(Player p) {


		if (p.getCoins()==0) 
			return true;
		else
			return false;
	}


}
